var request = require('request');
var cheerio = require('cheerio');
var md5 = require("md5");
var mysql = require('mysql');
var moment = require('moment');
var async = require('async');
 var db = require('./data/config');

var fun = require('./libs/func');


 var connection = mysql.createConnection({
 	host: db.host,
 	user: db.user,
 	password: db.password,
 	database:db.database
 });



    var args = process.argv.splice(2);
    console.log(args[0]);
    // exit;
    page = args[0]

    var options = {
    	url: 'http://cdfgj.gov.cn/SCXX/ShowNew.aspx?page='+page,
    	method: 'GET',
    	charset: "utf-8",
    	headers: {
    		"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36",
    	}
    };

    request(options, function(err, result) {
    	if (err) {
    		console.log(err);
    	}
    	//  console.log(result.body);

    	var $ = cheerio.load(result.body);

        var data = [];

        $('table[id^="ID_ucShowNew_gridView"]').find("tr").each(function(index,element){
        //    console.log($(element));

        tmp = []
        $(element).find("td").each(function(a,b){
        //    console.log(trim($(b).text()));
            tmp.push(fun.trim($(b).text()))

        })

        data.push(tmp)
    // console.log(tmp[7])

       })

     // console.log(data[1][2])
    re = []
    for (var i = 1; i < data.length; i++) {
        // console.log(data[i][5])

        data[i][8] = setdata(i,data)
        data[i][9] = md5(data[i][0]+data[i][6])
        re[i] = data[i]

    }

connection.connect();

        for (var i = 1; i < re.length; i++) {
            console.log(re[i])

var addSql  = 'INSERT INTO `cdfgj_history` (`uid`, `areas`, `qu`, `adress`, `used`, `companys`, `totals`, `date`, `dates`, `hashs`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);'

			 connection.query(addSql, re[i], function(err, result) {
    		 	if (err) {
    		 		console.log('[INSERT ERROR] - ', err.message);
    		 		return;
    		 	}
            //
    		 	//console.log('--------------------------INSERT----------------------------');
    		 	//console.log('INSERT ID:',result.insertId);
    		 	//console.log('INSERT ID:', result);
    		 	//console.log('-----------------------------------------------------------------\n\n');
    		 });


        }

connection.end();


	// var addSql = 'INSERT IGNORE  INTO cdfgj_trade(traderdate,areas,totals,housenum,housetotals,isones,hashs) VALUES(?,?,?,?,?,?,?)';





    })



function setdata(n=1,array){
    for (var i = n; i < array.length; i++) {
        if(array[i][7]!='现房'){
            return array[i][7]
        }
    }
}
